package com.jmyd.coupon.server.interceptors;

import com.jmyd.commons.constants.Constant;
import com.jmyd.commons.constants.JwtConstant;
import com.jmyd.commons.constants.RedisConstants;
import com.jmyd.commons.domain.po.SysUser;
import com.jmyd.commons.enums.SystemErrorEnum;
import com.jmyd.commons.redis.repository.StringRedisHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局前置拦截器
 *
 * @author samphin
 * @since 2020-12-8 11:43:57
 */
@Slf4j
public class GlobalPreInterceptor extends BaseInterceptor {

    @Resource
    private RedisTemplate<String, SysUser> redisTemplate;
    @Resource
    private StringRedisHelper stringRedisHelper;

    /**
     * 针对白名单的接口作access_token续期操作
     *
     * @param request  请求对象
     * @param response 响应对象
     * @param handler  代理对象
     * @author samphin
     * @since 2021-5-24 18:07:04
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) {
        String accessToken = request.getHeader(JwtConstant.AUTHORIZATION);
        //如果接口包含/platform代表开放平台相关接口
        if (StringUtils.isEmpty(accessToken)) {
            return returnResponseData(response, SystemErrorEnum.TOKEN_IS_EMPTY);
        }

        if (!stringRedisHelper.hasKey(String.format(RedisConstants.PREFIX_API_ACCESS_TOKEN, accessToken))) {
            return returnResponseData(response, SystemErrorEnum.TOKEN_INVALID_ERROR);
        }

        //设置access_token，将redis缓存的时间设置成jwtToken的2倍，保证缓存值能取到，如果缓存过期了说明token肯定过期了
        SysUser sysUser = redisTemplate.opsForValue().get(String.format(RedisConstants.PREFIX_API_ACCESS_TOKEN, accessToken));
        if (sysUser != null) {
            request.getSession().setAttribute(Constant.USER_ID, sysUser.getId());
            request.getSession().setAttribute(Constant.USER, sysUser);
        }
        return true;
    }
}
